﻿
using System;
using System.Linq;
using System.Security.Claims;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using SmallShop.Frame;
using SmallShop.BaseWeb;
using SmallShop.Bll;

namespace SmallShop.ManagerWeb.Controllers
{
    [AllowAnonymous]
    public class LoginController : SmallController
    {
        [HttpGet]
        public ActionResult Index(string returnUrl)
        {
            ViewBag.ReturnUrl = returnUrl??"/";
            return View();
        }

        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="n"></param>
        /// <param name="p"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Index(string n , string p)
        {
            if (n.IsNullOrEmpty())
            {
                return Json(new ResultModel {Message = "无效的用户名", Code = ResultModel.InValid});
            }
            if (p.IsNullOrEmpty())
            {
                return Json(new ResultModel { Message = "无效的密码", Code = ResultModel.InValid });
            }
            var biz = new ManagerBiz();
            var m = biz.Query().FirstOrDefault(it=>it.LoginName== n);
            if (m == null || m.Pwd != p)
            {
                return Json(new ResultModel { Message = "用户名或密码错误" ,Code = ResultModel.Failure });
            }

            FormsAuthentication.SetAuthCookie(m.LoginName, true, FormsAuthentication.FormsCookiePath);
            var user = new UserInfo { Name = m.LoginName, Id = m.Id, Role = "Admin"};
            var formTicket = new FormsAuthenticationTicket(1, m.LoginName, DateTime.Now, DateTime.Now.AddMinutes(20),
                false, user.ToJson());
          
            var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(formTicket));
            cookie.HttpOnly = true;
            HttpContext.Response.Cookies.Add(cookie);
            SetCurrentUser(user);
            return Json(new ResultModel());
        }

         
    }
}
